%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     网络通讯连接接收服务
%%% @end
%%%-------------------------------------------------------------------
-module(net_tcp_accepter_srv).

-behaviour(gen_server).

-export([start_link/2]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).

-include("common.hrl").
-include("env.hrl").

-record(state, {module, listen_socket}).


%%%===================================================================
%%% Spawning and gen_server implementation
%%%===================================================================

start_link(ListenSocket, Idx) ->
    gen_server:start_link(?MODULE, [ListenSocket, Idx], [{spawn_opt, [{scheduler, Idx}]}]).


init([ListenSocket, Idx]) ->
    Name = util_type:list_to_atom(lists:concat([?MODULE_STRING, "_", Idx])),
    erlang:register(Name, erlang:self()),

    ?ECHO("完成启动[~w]", [Name]),

    {ok, #state{module = env_mgr:get(?ENV_NET_PROTOCOL_HANDLER), listen_socket = ListenSocket}, 0}.

handle_call(_Request, _From, State) ->
    {reply, ok, State}.

handle_cast(_Request, State) ->
    {noreply, State}.

handle_info(timeout, State = #state{module = Module, listen_socket = ListenSocket}) ->
    case gen_tcp:accept(ListenSocket) of
        {ok, Socket} ->
            gen_tcp:controlling_process(Socket, erlang:spawn(fun() -> Module:on_accept(Socket) end));
        {error, closed} ->
            ok;
        {error, Reason} ->
            ?ERR("accept 错误:~p", [Reason])
    end,
    {noreply, State, 0};

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.
